

import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class OPMLparse {
	private String OpmlURL ;
	OPMLJavaBeans opmlBeans = null;
	List<OPMLJavaBeans> lists;
	Map<String, List<OPMLJavaBeans>> map;
	String ItemName = null;
	private boolean flag =false;
	String title = null;
	String xmlUrl = null;
	public OPMLparse(String url){//constructor,get input url;
		OpmlURL = url;
	}
	public void OpmlXmlResolve() throws Exception
	{
		
		DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = bf.newDocumentBuilder();
		InputStream inSteam = new URL(OpmlURL).openStream();
		Document doc = builder.parse(inSteam); 
		NodeList nl = doc.getElementsByTagName("outline");
		lists = new ArrayList<OPMLJavaBeans>();
		map = new HashMap<String, List<OPMLJavaBeans>>();
		for (int i = 0; i < nl.getLength(); i++) {
			
			Element e = (Element)nl.item(i);
			 title = e.getAttribute("title");
			 xmlUrl = e.getAttribute("xmlUrl");

			 if (xmlUrl == "") {
				if (ItemName == null) {
					ItemName = title;
				}
				else{
					map.put(ItemName, lists);
					lists = new ArrayList<OPMLJavaBeans>();
					ItemName = title;
				}
			} else {
				if (i != nl.getLength() -1) {
					opmlBeans = new OPMLJavaBeans();
					opmlBeans.setTitle(title);
					opmlBeans.setXmlUrl(xmlUrl);
					lists.add(opmlBeans);
				}
				else{
					opmlBeans = new OPMLJavaBeans();
					opmlBeans.setTitle(title);
					opmlBeans.setXmlUrl(xmlUrl);
					lists.add(opmlBeans);
					map.put(ItemName, lists);
				}
			}
		}	
		System.out.println(map.size());
//		Map<String, List<OPMLJavaBeans>> tempMap = new HashMap<String, List<OPMLJavaBeans>>(); 
		for ( Entry<String, List<OPMLJavaBeans>> entry : map.entrySet()) {
			System.out.println(entry.getKey()+":");
			String key = entry.getKey();
			for (int i = 0; i < map.get(key).size();i++){
				System.out.println("         "+map.get(key).get(i).getTitle());
			}
		}
		
		
		
		
}}